package com.example.demo.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2023-01-05
 * Time: 17:21
 */

/**
 * 数据返回格式统一处理
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    //此处修改为 返回true,才会执行下面的方法
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    //在返回前将返回数据进行处理成统一格式
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //构造统一返回数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", body);
        return result;
    }
}
